<?php
/**
 * Arr
 * Created by Veyron
 * motto:现在的拼搏 为了更好的明天
 * day:  2020/2/8
 * Time: 17:21
 */

namespace app\common\lib;


class Arr
{
    /**
     * 分类树——支持无限分类
     * @param $data
     */
    public static function getTree($data){
        $items = [];
        foreach ($data as $v){
            $items[$v['category_id'] ] = $v;
        }

        $tree = [];
        foreach ($items as $id=>$item){
            if(isset($items[$item['pid']])){
                $items[$item['pid']]['list'][] = &$items[$id];
            }else{
                $tree[] = &$items[$id];
            }
        }
        return $tree;
    }

    /**
     * 截取固定长度的分类
     * @param $data
     * @param int $firstCount
     * @param int $secondCount
     * @param int $threeCount
     * @return array
     */

    public static function sliceTreeArr($data, $firstCount = 5, $secondCount = 3, $threeCount = 5) {
        $data = array_slice($data, 0, $firstCount);
        foreach($data as $k => $v) {
            if(!empty($v['list'])) {
                $data[$k]['list'] = array_slice($v['list'], 0, $secondCount);
                foreach($v['list'] as $kk => $vv) {
                    if(!empty($vv['list'])) {
                        $data[$k]['list'][$kk]['list'] = array_slice($vv['list'], 0, $threeCount);
                    }
                }
            }
        }

        return $data;
    }



    /**
     * 分页默认返回的数据
     * @param $num
     * @return array
     */
    public static function getPaginateDefaultData($num){
        return [
            'total'         => 0,
            'per_page'      => $num,
            'current_page'  => 1,
            'last_page'     => 0,
            'data'          => [],
        ];
    }

    /**
     * 二维数组按照键名排序
     * @param $result
     * @param $key
     * @return array|bool
     */
    public static function arrSortByKey($result, $key, $sort = SORT_DESC){
        if(!is_array($result) || !$key){
            return [];
        }
        array_multisort(array_column($result,'create_time'),$sort,$result);
        return $result;
    }
}

